﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFML.Graphics;

namespace Theta.Components
{
    public class ComponentContainer : IDisposable
    {
        Dictionary<Type, BaseComponent> _components;
        
        public ComponentContainer()
        {
            _components = new Dictionary<Type, BaseComponent>();
        }

        public void AddComponent<T>(T component) where T : BaseComponent
        {
            if (_components.ContainsKey(typeof(T)))
                throw new ArgumentException("The component is already added to the list, component type: " + typeof(T).FullName);
            _components.Add(typeof(T), component);
        }

        public bool ContainsComponent<T>()
        {
            return _components.ContainsKey(typeof(T));
        }

        public void RemoveComponent<T>(bool dispose) where T : BaseComponent
        {
            T obj = (T)_components[typeof(T)];
            
            if(dispose)
            {
                IDisposable d = obj as IDisposable;
                if(d != null)
                    d.Dispose();
            }
            obj.Parent = null;

            _components.Remove(typeof(T));
        }

        public T GetComponent<T>() where T : BaseComponent
        {
            Type t = typeof(T);

            if (_components.ContainsKey(t))
            {
                return (T)_components[t];
            }

            return null;
        }

        public void Update(TimeSpan elapsedTime)
        {
            foreach(KeyValuePair<Type, BaseComponent> baseComponent in _components)
            {
                 baseComponent.Value.Update(elapsedTime);
            }
        }

        public void Draw(RenderWindow rd)
        {
            foreach(KeyValuePair<Type, BaseComponent> keyValuePair in _components)
            {
                keyValuePair.Value.Draw(rd);
            }
        }

        public void Dispose()
        {
            foreach(KeyValuePair<Type, BaseComponent> o in _components)
            {   
                //Doing this makes sure OnRemove gets called in the component
                //TODO: This should be replaced by something else as it's obscure (only setting Component.Parent to null triggers OnRemove)
                o.Value.Parent = null;
  
                IDisposable d = o.Value as IDisposable;
                if(d != null)
                    d.Dispose();
            }
        }
    }
}
